import qs from "qs";
import axios from 'axios'
import {Notification, MessageBox, Message} from 'element-ui'

// axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: 'http://localhost:9000',
    // baseURL: 'http://localhost/api',
    // 超时
    timeout: 30000
})
// request拦截器
service.interceptors.request.use(config => {
    let token = sessionStorage.getItem('token');
    let expireTime = sessionStorage.getItem('expireTime');
    let time = new Date().getTime();
    if (token != null && token != undefined && expireTime - time > 0) {
        config.headers.token = token
    }
    return config
}, error => {
    console.log(error)
    Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
        // 未设置状态码则默认成功状态
        const code = res.data.code || 200;
        // 获取错误信息
        const message = res.data.message
        if (code === 401) {
            MessageBox.confirm(
                '登录状态已过期，您可以继续留在该页面，或者重新登录',
                '系统提示',
                {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).then(() => {
                location.reload()
                // store.dispatch('LogOut').then(() => {
                //   location.reload() // 为了重新实例化vue-router对象 避免bug
                // })
            })
        } else if (code === 500 || code === 402 || code === 403) {
            Message({
                message: message,
                type: 'error'
            })
            // return Promise.reject(new Error(message))
            return new Promise(() => {
            })

        } else if (code !== 200) {
            Notification.error({
                title: message
            })
            // return Promise.reject('error')
            return new Promise(() => {
            })
        } else {
            return res.data
        }
    },
    error => {
        console.log('err' + error)
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

const http = {
    post(url, params) {
        return service.post(url, params, {
            transformRequest: [(params) => {
                return JSON.stringify(params)
            }],
            headers: {
                'Content-Type': 'application/json'
            }
        })
    },
    put(url, params) {
        return service.put(url, params, {
            transformRequest: [(params) => {
                return JSON.stringify(params)
            }],
            headers: {
                'Content-Type': 'application/json'
            }
        })
    },
    //get请求传递对象
    get(url, params) {
        return service.get(url, {
            params: params,
            paramsSerializer: (params) => {
                return qs.stringify(params)
            }
        })
    },
    //get请求路径参数
    getRestApi(url, params) {
        let _params
        if (Object.is(params, undefined || null)) {
            _params = ''
        } else {
            _params = '/'
            for (const key in params) {
                // console.log(key)
                // console.log(params[key])
                // eslint-disable-next-line no-prototype-builtins
                if (params.hasOwnProperty(key) && params[key] != null && params[key] != '') {
                    _params += `${params[key]}/`
                }
            }
            _params = _params.substr(0, _params.length - 1)
        }
        if (_params) {
            return service.get(`${url}${_params}`)
        } else {
            return service.get(url)
        }
    },
    delete(url, params) {
        let _params
        if (Object.is(params, undefined || null)) {
            _params = ''
        } else {
            _params = '/'
            for (const key in params) {
                // eslint-disable-next-line no-prototype-builtins
                if (params.hasOwnProperty(key) && params[key] !== null && params[key] !== '') {
                    _params += `${params[key]}/`
                }
            }
            _params = _params.substr(0, _params.length - 1)
        }
        if (_params) {
            return service.delete(`${url}${_params}`).catch(err => {
                // eslint-disable-next-line no-undef
                message.error(err.msg)
                return Promise.reject(err)
            })
        } else {
            return service.delete(url).catch(err => {
                // eslint-disable-next-line no-undef
                message.error(err.msg)
                return Promise.reject(err)
            })
        }
    },
    upload(url, params) {
        return service.post(url, params, {
            // headers: {
            //     'Content-Type': 'multipart/form-data'
            // }
        })
    },
    download(url, params) {
        return service.post(url, params, {
            responseType:'blob',
        }).then(res =>{
            const url = window.URL.createObjectURL(res);
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', '租金统计下载.xlsx'); //or any other extension
            document.body.appendChild(link);
            link.click();
            // console.log(res)
            // let blob = new Blob([res.data], { type: 'application/octet-stream' })
            // let url = window.URL.createObjectURL(blob)
            // let link = document.createElement('a')
            // link.style.display = 'none'
            // link.href = url
            // // 文件名一般是在res.headers里：content-disposition;fileName=xxxxxxxxxx.csv，这个让后端统一规定文件名怎么放前端就怎么取就行
            // let str = typeof res.headers['Content-Disposition'] === 'undefined'
            //     ? res.headers['Content-Disposition'].split(';')[1]
            //     : res.headers['content-disposition'].split(';')[1]
            //
            // let filename = typeof str.split('fileName=')[1] === 'undefined'
            //     ? str.split('filename=')[1]
            //     : str.split('fileName=')[1]
            // link.setAttribute('download', decodeURIComponent(filename)) // 解码，这里也可以自定义下载的文件名字，如link.setAttribute('download', 'xxxxxdownload.xls')
            // document.body.appendChild(link)
            // link.click() //用新窗口打开window.open(link.click())，但是下载完成后不会先get请求那样自动关闭窗口
        }).catch(error =>{
            console.log(error)
        })
    },
    login(url, params) {
        return service.post(url, params, {
            transformRequest: [(params) => {
                return qs.stringify(params)
            }],
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
    }
}

export default http